<?php 
/**
#	Project: PHPDISK File Storage Solution
#	This is NOT a freeware, use is subject to license terms.
#
#	Site: http://www.phpdisk.com
#
#	$Id: database.inc.php 4 2013-01-09 13:32:24Z along $
#
#	Copyright (C) 2008-2013 PHPDisk Team. All Rights Reserved.
#
*/

if(!defined('IN_PHPDISK') || !defined('IN_ADMINCP')) {
	exit('[PHPDisk] Access Denied');
}

require PHPDISK_ROOT.'includes/function/database.func.php';

switch($action){

	case 'backup':
	case 'optimize':

		if($task =='optimize'){
			if($settings['online_demo']){
				$error = true;
				$sysmsg[] = __('online_demo_deny');
			}

			if(!$error){
				$q = $db->list_tables($configs['dbname']);
				if($q){
					while ($rs = $db->fetch_row($q)){
						if(substr($rs[0],0,3) == $tpf){
							$tables[][] = $rs[0];
						}
					}
				}
				$db->free($q);
				unset($rs);

				for($i=0;$i<count($tables);$i++){
					$db->query("OPTIMIZE TABLE `".$tables[$i][0]."`;");
				}
				$sysmsg[] = __('optimize_success');
				redirect(urr(ADMINCP,"item=database&menu=tool&action=$action"),$sysmsg);
			}else{
				redirect('back',$sysmsg);
			}

		}elseif($task =='backup'){
			if($settings['online_demo']){
				$error = true;
				$sysmsg[] = __('online_demo_deny');
			}

			$tables = gpc('tables','P',array());
			$tableid = gpc('tableid','G',0);
			$fileid = (int)gpc('fileid','G',0);
			$startfrom = (int)gpc('startfrom','G',0);
			$random = gpc('random','G','');
			$sizelimit = (int)gpc('sizelimit','GP',0);
			$fileid = $fileid ? $fileid : 1;

			$sizelimit = $sizelimit ? (int)$sizelimit : 2048;

			$bak_dir = PHPDISK_ROOT.'system/data/';
			make_dir($bak_dir);

			if($tables && $fileid==1){
				if(!isset($tables) || !is_array($tables)){
					$sysmsg[] = __('please_select_backup_db');
					redirect($_SERVER['HTTP_REFERER'],$sysmsg);
				}

				$random = random(8);
				cache_write('backup_temp_tables.php', $tables);
			}else{
				if(!$tables = cache_read('backup_temp_tables.php')){
					$sysmsg[] = __('cannot_write_backup_database_list');
					redirect($_SERVER['HTTP_REFERER'],$sysmsg);
				}
			}

			$sql_data = '';
			$tableid = $tableid ? ($tableid - 1) : 0;
			$startfrom = $startfrom ? $startfrom : 0;
			$tablenumber = count($tables);

			for($i = $tableid; $i < $tablenumber && strlen($sql_data) < $sizelimit * 1000; $i++){
				$sql_data .= sql_dumptable($tables[$i], $startfrom, strlen($sql_data));
				$startfrom = 0;
			}

			if(!$error){
				if(trim($sql_data)){
					$sqldump = "# Database backup file, auto-generated by PHPDISK. ".LF;
					$sqldump .= "# -------------------------------------------".LF.LF.$sql_data;

					$tableid = $i;
					$filename = $configs['dbname'].'_'.date('Ymd').'_'.$random.'_'.$fileid.'.sql';
					$fileid++;

					$bakfile = $bak_dir.$filename;
					if(!is_writable($bak_dir)){
						$sysmsg[] = __('sql_cannot_write');
						redirect($_SERVER['HTTP_REFERER'],$sysmsg);
					}
					file_put_contents($bakfile, $sqldump);

					$gourl = 'item=database&menu=tool&action=backup&task=backup&sizelimit='.$sizelimit.'&tableid='.$tableid.'&fileid='.$fileid.'&startfrom='.$startrow.'&random='.$random;
					$sysmsg[] = __('backup_file').': '.$filename.' ... '.__('backup_write_success');
					$sysmsg[] = '<span class="txtred">'.__('backup_database_warning').'</span>';
					redirect(urr(ADMINCP,$gourl),$sysmsg);

				}else{
					cache_delete('backup_temp_tables.php');
					$sysmsg[] = __('backup_database_success');
					redirect(urr(ADMINCP,"item=database&menu=tool&action=restore"),$sysmsg);
				}
			}else{
				redirect('back',$sysmsg);
			}
		}else{
			$size = $bktables = $bkresults = $results = array();
			$k = 0;
			$totalsize = 0;
			$q = $db->query("SHOW TABLE STATUS FROM `".$configs['dbname']."` LIKE '{$tpf}%'");
			$table_arr = array();
			while($rs = $db->fetch_array($q)){
				$table_arr[] = $rs;
			}
			$db->free($q);
			unset($rs);
			require_once template_echo($item,$admin_tpl_dir,'',1);
		}
		break;

	case 'restore':
		if($task =='restore'){
			if($settings['online_demo']){
				$error = true;
				$sysmsg[] = __('online_demo_deny');
			}

			$pre = gpc('pre','G','');
			$fileid = (int)gpc('fileid','G',0);

			if(!$error){
				if($filename && get_extension($filename)=='sql'){

					$sql_file = PHPDISK_ROOT.'./system/data/'.$filename;
					if(!file_exists($sql_file)){
						$sysmsg[] = $sql_file.' ...... '.__('file_not_exists');
						redirect(urr(ADMINCP,"item=database&menu=tool&action=restore"),$sysmsg);
					}
					$sql = file_get_contents($sql_file);
					sql_execute($sql);
					$sysmsg[] = __('restore_database_success');
					redirect(urr(ADMINCP,"item=database&menu=tool&action=backup"),$sysmsg);

				}else{

					$fileid = $fileid ? $fileid : 1;
					$filename = $pre.$fileid.'.sql';
					$sql_file = './system/data/'.$filename;
					if(file_exists($sql_file)){
						$sql = file_get_contents($sql_file);
						sql_execute($sql);
						$fileid++;
						$sysmsg[] = __('backup_file').': '.$filename.' ...... '.__('restore_sucess');
						$sysmsg[] = '<span class="txtred">'.__('restore_database_warning').'</span>';
						$gourl = "item=database&menu=tool&action=restore&task=restore&pre=$pre&fileid=$fileid";
						redirect(urr(ADMINCP,$gourl),$sysmsg);

					}else{
						$sysmsg[] = __('restore_database_success');
						redirect(urr(ADMINCP,"item=database&menu=tool&action=restore"),$sysmsg);
					}
				}
			}else{
				redirect('back',$sysmsg);
			}

		}else{

			$sqlfiles = glob(PHPDISK_ROOT.'system/data/*.sql');

			if(is_array($sqlfiles)){
				$prepre = '';
				$info = $infos = array();
				foreach($sqlfiles as $k => $sqlfile)
				{
					preg_match("/([a-z0-9_]+_[0-9]{8}_[0-9a-z]{8}_)([0-9]+)\.sql/i",basename($sqlfile),$num);
					$info['filename'] = basename($sqlfile);
					$info['filesize'] = round(filesize($sqlfile)/(1024*1024), 2);
					$info['maketime'] = date('Y-m-d H:i:s', filemtime($sqlfile));
					$info['pre'] = $num[1];
					$info['number'] = $num[2];
					if(!$k) $prebgcolor = '#fafafa';
					if($info['pre'] == $prepre){
						$info['bgcolor'] = $prebgcolor;
					}else{
						$info['bgcolor'] = $prebgcolor == '#fafafa' ? '#E4EDF9' : '#fafafa';
					}
					$prebgcolor = $info['bgcolor'];
					$prepre = $info['pre'];
					$info['a_delete'] = urr(ADMINCP,"item=database&menu=tool&action=delete&pre={$info['pre']}");
					$info['a_restore'] = urr(ADMINCP,"item=database&menu=tool&action=restore&task=restore&pre={$info['pre']}");
					$infos[] = $info;
				}
			}
			require_once template_echo($item,$admin_tpl_dir,'',1);
		}
		break;

	case 'delete':
		if($settings['online_demo']){
			$error = true;
			$sysmsg[] = __('online_demo_deny');
		}
		if(!$error){
			$pre = gpc('pre','G','');
			$sqlfiles = glob(PHPDISK_ROOT.'system/data/*.sql');
			if(is_array($sqlfiles)){
				foreach($sqlfiles as $k => $sqlfile){
					if(preg_match("/($pre)([0-9]+)\.sql/i",basename($sqlfile))){
						$sysmsg[] = __('delete').'&nbsp;&nbsp;'.$sqlfile.' ...... '.__('success');
						@unlink($sqlfile);
					}
				}
			}
			redirect(urr(ADMINCP,"item=database&menu=tool&action=restore"),$sysmsg);
		}else{
			redirect('back',$sysmsg);
		}
		break;

	default:
		redirect(urr(ADMINCP,"item=database&menu=tool&action=backup"),$sysmsg);
}

?>